# -*- coding:utf8 -*-
import wiringpi as gpio
import requests
from datetime import datetime
import json

yeelink_api_t = 'http://api.yeelink.net/v1.1/device/361230/sensor/412500/datapoints'
yeelink_api_h = 'http://api.yeelink.net/v1.1/device/361230/sensor/412501/datapoints'
yeelink_key = '126e92ae9c460c5ee2e81cebc0545f8f'

gpio.wiringPiSetupPhys()

def get_dht11():
	try:
		while True:
			gpio.pinMode(11, gpio.OUTPUT)
			gpio.digitalWrite(11, gpio.HIGH)
			gpio.delay(1)
			gpio.digitalWrite(11, gpio.LOW)
			gpio.delay(18)
			gpio.digitalWrite(11, gpio.HIGH)
			gpio.pinMode(11, gpio.INPUT)
			while gpio.digitalRead(11) == 1:
				continue
			while gpio.digitalRead(11) == 0:
				continue
			while gpio.digitalRead(11) == 1:
				continue
			data = []
			j = 1
			while j < 40:
				tc = gpio.micros()
      
				while gpio.digitalRead(11) == 0:
					continue
      
      
				while gpio.digitalRead(11) == 1:
					if gpio.micros() - tc > 500:
						break
				if gpio.micros() - tc > 500:
					break
				data.append(gpio.micros() - tc)

			if not len(data) == 40:
				print(len(data))
				gpio.delay(2000)
				continue
			data = ''.join(['1' if d > 100 else '0' for d in data])
			hi = int(data[:8], 2)
			hd = int(data[8:16], 2)
			ti = int(data[16:24], 2)
			td = int(data[24:32], 2)
			check = int(data[32:], 2)
			if not (hi+hd+ti+td) == check:
				gpio.delay(2000) 
				continue
			temperature = float("{}.{}".format(ti, td))
			humidity = float("{}.{}".format(hi, hd))
			return (temperature, humidity)
	except KeyboardInterrupt as e:
		raise e

def push_yeelink(temperture, humidity):
	pdata = {
		'timestamp': datetime.today().strftime('%Y-%m-%dT%H:%M:%S'),
		'value': temperture
	}
	try:
		res = requests.post(yeelink_api_t, data=json.dumps(pdata), headers={'U-ApiKey': yeelink_key})
		print(res, res.content.decode())
		pdata['value'] = humidity
		res = requests.post(yeelink_api_h, data=json.dumps(pdata), headers={'U-ApiKey': yeelink_key})
		print(res, res.content.decode())
		return True
	except Exception as e:
		return False

if __name__ == '__main__':
	try:
		while True:
			t, h = get_dht11()
			print('温度: {}, 湿度: {}'.format(t, h))
			with open('temp.txt', 'w') as f:
				f.write('{},{}'.format(t, h))
			#if not push_yeelink(t, h):
			#	gpio.delay(2000)
			#	continue
			gpio.delay(1000)
	except KeyboardInterrupt:
		pass
